package web

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"ocr/ocr"
	"strconv"
)

func RecognizeHealthCodeOCRHandler(rw http.ResponseWriter, req *http.Request) {
	var request = ocr.NewRecognizeHealthCodeOCRRequest()
	imageUrl := req.FormValue("image_url")
	type1, _ := strconv.ParseInt(req.FormValue("type"), 10, 64)

	request.ImageUrl = &imageUrl
	request.Type = &type1

	if imageUrl == "" {
		file, _, err := req.FormFile("image_file")
		if err != nil {
			log.Println(err.Error())
			return
		}
		bytes, err := ioutil.ReadAll(file)
		if err != nil {
			log.Println(err.Error())
			return
		}
		imageBase64 := base64.StdEncoding.EncodeToString(bytes)
		request.ImageBase64 = &imageBase64
	}

	response, err := ocr.RecognizeHealthCodeOCR(request)
	if err != nil {
		log.Println(err.Error())
		return
	}
	fmt.Printf("%s", response.ToJsonString())
	fmt.Fprintf(rw, response.ToJsonString())
}
